package gfile

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

//PathExists ...
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if !os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

//GetFilePath ...
func GetFilePath(localPath string) string {
	//命令启动时的路径
	exists, _ := PathExists(localPath)
	if !exists {
		AppPath, err := filepath.Abs(filepath.Dir(os.Args[0]))
		if err != nil {
			panic(err)
		}
		//二进制启动时路径
		localPath = filepath.Join(AppPath, localPath)
	}

	return localPath
}

//GetExePath ...
func GetExePath() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	index := strings.LastIndex(path, string(os.PathSeparator))

	return path[:index]
}

func WriteFile(path string, content []byte, append bool) (bool, error) {
	var f *os.File
	var err error
	path = GetFilePath(path)
	if !append {
		RemoveFile(path)
	}

	if b, _ := PathExists(path); !b {
		_f, err := os.Create(path)
		if err != nil {
			return false, err
		}
		_f.Close()
	}

	if append {
		f, err = os.OpenFile(path, os.O_APPEND, 0666)
	} else {
		f, err = os.OpenFile(path, os.O_WRONLY, 0666)
	}

	if err != nil {
		return false, err
	}

	f.Write(content)
	f.Close()
	return true, nil
}

func RemoveFile(path string) {
	path = GetFilePath(path)
	os.Remove(path)
}

func ReadFile(path string) ([]byte, error) {
	path = GetFilePath(path)
	return ioutil.ReadFile(path)
}
